package com.quasar.hpatient.module.home_medicine_edit;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.home_medicine.MedicineBean;
import com.quasar.hpatient.bean.home_medicine_record.MedicineRecoedBean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.db.manager.DBManager;
import lib.quasar.db.table.Medicine;
import lib.quasar.recycler.BaseCommonAdapter;
import lib.quasar.recycler.BaseCommonMultAdapter;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.recycler.model.MultModel;
import lib.quasar.util.DimenUtil;
import lib.quasar.util.LogUtil;
import lib.quasar.util.SpannableUtil;
import lib.quasar.util.ToastUtil;
import lib.quasar.widget.edit.AlterEditText;
import lib.quasar.widget.menu.NextView;
import okhttp3.RequestBody;

/**
 * description: 编辑药单
 * created by kalu on 2018/5/4 10:48
 */
public class MedicineEditPresenter implements BasePresenter {

    public String getmName() {
        return mName;
    }

    public void setmName(String mName) {
        this.mName = mName;
    }

    private String mName = "";

    public String getmUnit() {
        return mUnit;
    }

    public void setmUnit(String mUnit) {
        this.mUnit = mUnit;
    }

    private String mUnit = "";

    public List<Medicine> getListMedicine() {
        return listMedicine;
    }

    private List<Medicine> listMedicine = null;

    public void initData(){

        listMedicine = DBManager.getInstance().getMedicineList();

    }

    private float getStep(float CurNum,int order){

        if (CurNum == 0 && order == 0)
            return (float)0.0;
        int mId = -1;
        List<Medicine> list1 = getListMedicine();
        if (null == list1)
            return (float)1.0;
        for (Medicine temp : list1) {
             if (getmName().equals(temp.getName())){
                 if ("".equals(getmUnit())){
                     mId = temp.getId_().intValue();
                     break;
                 }
                 else{
                     if (getmUnit().equals(temp.getDose())){
                         mId = temp.getId_().intValue();
                         break;
                     }
                     continue;
                 }


             }
        }
        switch (mId){
            case 10:
                if (order == 0){
                    if (CurNum <= 0.5)
                        return (float)0.25;
                    return (float)0.5;
                }else {
                    if (CurNum <0.5)
                        return (float)0.25;
                    return (float)0.5;
                }
            case 193:
            case 194:
            case 195:
                return (float)0.25;
            case 74:
            case 189:
                if (order == 0){
                    if (CurNum <= 1.0)
                        return (float)0.25;
                    return (float)0.5;
                }else {

                    if (CurNum < 1)
                        return (float)0.25;
                    return (float)0.5;
                }
            case 72:
            case 174:
            case 118:
            case 119:
            case 206:
                if (order == 0){

                    if (CurNum <= 1.0)
                        return (float)0.5;
                    return (float)1.0;
                }else {

                    if (CurNum < 1)
                        return (float)0.5;
                    return (float)1.0;
                }
            case 11:
            case 12:
            case 45:
            case 48:
            case 58:
            case 73:
            case 137:
            case 179:
            case 191:
            case 180:
            case 185:
            case 205:
                return (float)0.5;
            default:
                return (float)1.0;
        }

    }

    private String getDefaultDetail(String mName,String mUnit){
        List<Medicine> list1 = getListMedicine();
        if (null == list1)
            return "";
        for (Medicine temp : list1) {
            if (mName.equals(temp.getName())){
                if (mUnit.equals(getmUnit())){
                    //todo
                   return temp.getName();
                }
            }
        }
        return "";
    }

    private final List<MedicineBean.MedicineItemBean.MedicineItemDetailBean> mDatas = new LinkedList<>();

    {
        final MedicineBean.MedicineItemBean.MedicineItemDetailBean temp = new MedicineBean.MedicineItemBean.MedicineItemDetailBean();
        temp.setUse_order(Integer.MIN_VALUE);
        mDatas.add(temp);
    }

    void initList(final MedicineEditView view, RecyclerView recycler, List<MedicineBean.MedicineItemBean> list, int positions) {

        if (positions != -1 && null != list && list.size() > 0) {
            final MedicineBean.MedicineItemBean news = list.get(positions);
            if (null != news) {
                final List<MedicineBean.MedicineItemBean.MedicineItemDetailBean> newslist = news.getUse_detail();
                if (null != newslist && newslist.size() > 0) {
                    for (MedicineBean.MedicineItemBean.MedicineItemDetailBean temp : newslist) {
                        final MedicineBean.MedicineItemBean.MedicineItemDetailBean model = new MedicineBean.MedicineItemBean.MedicineItemDetailBean();
                        model.setUse_order(temp.getOrder());
                        model.setUse_time(temp.getUse_time());
                        model.setUse_number(temp.getUse_number());
                        mDatas.add(model);
                    }
                }
            }
        }

        recycler.setTag("1");
        final BaseCommonMultAdapter<MedicineBean.MedicineItemBean.MedicineItemDetailBean> adapter = new BaseCommonMultAdapter<MedicineBean.MedicineItemBean.MedicineItemDetailBean>(mDatas) {

            @Override
            protected void onMult() {
                addMult(MultModel.TYPE_0, R.layout.activity_home_medicine_edit_null);
                addMult(MultModel.TYPE_1, R.layout.activity_home_medicine_edit_child);
            }

            @Override
            protected void onNext(RecyclerHolder holder, final MedicineBean.MedicineItemBean.MedicineItemDetailBean model, final int position) {

                switch (model.getMultType()) {
                    case MultModel.TYPE_1:

                        AlterEditText edit = holder.getView(R.id.activity_home_medicine_edit_child_num);
                        edit.setNumberFilter(2, 4);
                        edit.setOnInputChangeListener((input, isDelete, isMax) -> {
                            if (".".equals(input) || "".equals(input)) return;

                            model.setUse_number(Float.parseFloat(input.toString()));
                        });
                        model.setUse_order(position);
                        view.setText(holder, R.id.activity_home_medicine_edit_child_order, model.getUse_order());
                        view.setText(holder, R.id.activity_home_medicine_edit_child_time, model.getShortUse_time());
                        view.setText(holder, R.id.activity_home_medicine_edit_child_num, String.valueOf(model.getUse_number()));

                        holder.setOnClickListener(R.id.activity_home_medicine_edit_child_time, v -> view.showTime(position));

                        holder.setOnClickListener(R.id.activity_home_medicine_edit_child_minus, v -> {
                            if (null == recycler.getTag())
                                return;
                            edit.clearFocus();
                            Float value = Float.parseFloat(edit.getText().toString()) - getStep(Float.parseFloat(edit.getText().toString()),0);
                            model.setUse_number(value < 0 ? 0f : value);
                            view.setText(edit, String.valueOf(model.getUse_number()));
                        });
                        holder.setOnClickListener(R.id.activity_home_medicine_edit_child_plus, v -> {
                            if (null == recycler.getTag())
                                return;
                            edit.clearFocus();
                            Float value = Float.parseFloat(edit.getText().toString()) + getStep(Float.parseFloat(edit.getText().toString()),1);
                            model.setUse_number(value < 0 ? 0f : value);
                            view.setText(edit, String.valueOf(model.getUse_number()));
                        });
                        holder.setOnClickListener(R.id.activity_home_medicine_edit_child_delete, v -> {

                            mDatas.remove(position);
                            calcuTime();
                            view.refreshList(recycler);
                        });
                        break;
                }
            }
        };

        final View head = LayoutInflater.from(BaseApp.getContext()).inflate(R.layout.activity_home_medicine_edit_head, null);
        head.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dp2px(396)));
        adapter.addHead(head);

        // 服药名称
        AutoCompleteTextView name = head.findViewById(R.id.activity_home_medicine_edit_head_names);
        view.setText(name, positions == -1 ? "" : list.get(positions).getMname());
        // 服药规格
        AutoCompleteTextView unit = head.findViewById(R.id.activity_home_medicine_edit_head_units);
        view.setText(unit, positions == -1 ? "" : list.get(positions).getDose_name());
        if (positions != -1) {

            // 单次量
            String[] split = list.get(positions).getDose_name().split("/");
            if (null != split && split.length == 2) {
                TextView value = head.findViewById(R.id.patient_medicine_edit_head_value);
                value.setText(split[1]);
            }

            name.setEnabled(false);
            name.setTextColor(BaseApp.getColors(R.color.color_bg_peach));
            unit.setEnabled(false);
            unit.setTextColor(BaseApp.getColors(R.color.color_bg_peach));
        }
        // 开始时间
        NextView time = head.findViewById(R.id.home_medicine_edit_head_time);
        time.setText(positions == -1 ? "" : list.get(positions).getPeriod_begindate());
        time.setOnClickListener(v -> view.showYear(time));
        // 服药方法
        NextView method = head.findViewById(R.id.home_medicine_edit_head_method);
        method.setText(positions == -1 ? "" : list.get(positions).getMethod());
        method.setOnClickListener(v -> view.showMethod());
        // 服药天数
        NextView day = head.findViewById(R.id.home_medicine_edit_head_day);
        day.setText(positions == -1 ? "" : calcuDay(list.get(positions).getPeriod_length()));
        day.setOnClickListener(v -> view.showDay());
        // 备注信息
        TextView remark = head.findViewById(R.id.home_medicine_edit_head_remark);
        view.setText(remark, positions == -1 ? "" : list.get(positions).getRemark());
        // 添加
        TextView add = head.findViewById(R.id.activity_home_medicine_edit_menu_add);
        add.setOnClickListener(v -> {
            mDatas.add(new MedicineBean.MedicineItemBean.MedicineItemDetailBean());
            calcuTime();
            view.refreshList(recycler);
            view.scrollRecycler(recycler, mDatas.size());
        });
        // 药品名字
        ArrayList<String> nameList = new ArrayList<>();
        List<Medicine> list1 = getListMedicine();
        for (Medicine temp : list1) {
            nameList.add(temp.getName());
        }
        ArrayAdapter<String> namesAdapter = new FilterAdapter(BaseApp.getContext(), android.R.layout.simple_list_item_1, nameList);
        name.setAdapter(namesAdapter);
        name.setOnClickListener(v -> {
            unit.setText("");
            name.showDropDown();
        });

        ArrayList<String> unitList = new ArrayList<>();
        ArrayAdapter<String> unitsAdapter = new FilterAdapter(BaseApp.getContext(), android.R.layout.simple_list_item_1, unitList);
        unit.setAdapter(unitsAdapter);
        name.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
//                String names = name.getText().toString();
//                if (TextUtils.isEmpty(names)) return;
//
//                List<Medicine> medicineList = DBManager.getInstance().getMedicineList(names);
//                if (null == medicineList || medicineList.isEmpty()) return;
//
//                unitList.clear();
//                for (Medicine temp : medicineList) {
//                    unitList.add(temp.getDose());
//                }
//                unit.showDropDown();
                return;
            }else{
               // view.setText(unit, "");
                name.showDropDown();
            }

        });
        // 编辑药品名称： 药品规格清空
        name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
               // unit.setText("");
            }
        });
        name.setOnItemClickListener((parent, view1, position, id) -> {
            String nameStr = nameList.get(position);
            setmName(nameStr);
            view.setText(name, nameStr);
            view.setSelection(name, nameStr.length());
            //name.dismissDropDown();
            view.clearFocus(name);
            unit.requestFocus();
        });

//        name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (!hasFocus){
//
//                }
//            }
//        });
        // 药品规格
        //ArrayList<String> unitList = new ArrayList<>();

        unit.setOnItemClickListener((parent, view12, position, id) -> {
            // 规格
            String units = unitList.get(position);
            setmUnit(units);
            if (TextUtils.isEmpty(units)) return;
            unit.setText(units);

            // 单位
            String[] split = units.split("/");
            if (null != split && split.length == 2) {
                TextView value = head.findViewById(R.id.patient_medicine_edit_head_value);
                value.setText(split[1]);
            }

            // 药名
            String names = name.getText().toString();
            if (TextUtils.isEmpty(names)) return;

            Medicine medicine = DBManager.getInstance().getMedicine(names, units);
            if (null != medicine) {
                recycler.setTag(medicine.getStep());
            }

            unit.setSelection(units.length());
            unit.clearFocus();
            refreshList(view, recycler, list, name, unit, time, method, day, remark);
        });
        unit.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) return;
            time.setText(getDateLittle());
            method.setText("每天服用");
            day.setText("长期");
            remark.setText("");


            String names = name.getText().toString();
            if (TextUtils.isEmpty(names)) return;

            List<Medicine> medicineList = DBManager.getInstance().getMedicineList(names);
            if (null == medicineList || medicineList.isEmpty()) return;

            unitList.clear();
            for (Medicine temp : medicineList) {
                unitList.add(temp.getDose());
            }
            if (unitList.size() == 1){
                // 单位
                unit.setText(unitList.get(0));
                String[] split = unitList.get(0).split("/");
                if (null != split && split.length == 2) {
                    TextView value = head.findViewById(R.id.patient_medicine_edit_head_value);
                    value.setText(split[1]);
                }

            }

            else
                unit.showDropDown();
        });
        unit.setOnClickListener(v -> {
            String names = name.getText().toString();
            if (TextUtils.isEmpty(names)) return;

            List<Medicine> medicineList = DBManager.getInstance().getMedicineList(names);
            if (null == medicineList || medicineList.isEmpty()) return;

            unitList.clear();
            for (Medicine temp : medicineList) {
                unitList.add(temp.getDose());
            }
            unit.showDropDown();
        });
        unit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {

//                time.clearText();
//                method.clearText();
//                day.clearText();
//                remark.setText("");


//                if (mDatas.size() == 1 && mDatas.get(0).getMultType() == MultModel.TYPE_0) return;
//                mDatas.clear();
//                final MedicineBean.MedicineItemBean.MedicineItemDetailBean temp = new MedicineBean.MedicineItemBean.MedicineItemDetailBean();
//                temp.setUse_order(Integer.MIN_VALUE);
//                mDatas.addFirst(temp);

            }
        });

        final View foot = LayoutInflater.from(BaseApp.getContext()).inflate(R.layout.activity_home_medicine_edit_foot, null);
        final int height2 = DimenUtil.dp2px(50);
        RecyclerView.LayoutParams params2 = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height2);
        params2.topMargin = DimenUtil.dp2px(20);
        params2.leftMargin = DimenUtil.dp2px(20);
        params2.rightMargin = DimenUtil.dp2px(20);
        params2.bottomMargin = DimenUtil.dp2px(50);
        foot.setLayoutParams(params2);
        foot.setVisibility(positions == -1 ? View.INVISIBLE : View.VISIBLE);
        adapter.addFoot(foot);
        foot.setOnClickListener(v -> view.showDelete(positions));

        adapter.setNullView(BaseApp.getContext(), R.layout.layout_recycler_loading);
        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        view.setRecycler(recycler, adapter, manager);
    }

    void setMethod(RecyclerView recycler, String method) {

        if (null == recycler || TextUtils.isEmpty(method)) return;

        RecyclerView.Adapter adapter = recycler.getAdapter();
        if (null == adapter || !(adapter instanceof BaseCommonAdapter)) return;

        BaseCommonAdapter adapter1 = (BaseCommonAdapter) adapter;
        LinearLayout head = adapter1.getHead();
        if (null == head) return;

        NextView text = head.findViewById(R.id.home_medicine_edit_head_method);
        if (null == text) return;
        text.setText(method);
    }

    void setDay(RecyclerView recycler, String day) {

        if (null == recycler || TextUtils.isEmpty(day)) return;

        RecyclerView.Adapter adapter = recycler.getAdapter();
        if (null == adapter || !(adapter instanceof BaseCommonAdapter)) return;

        BaseCommonAdapter adapter1 = (BaseCommonAdapter) adapter;
        LinearLayout head = adapter1.getHead();
        if (null == head) return;

        NextView text = head.findViewById(R.id.home_medicine_edit_head_day);
        if (null == text) return;
        text.setText(day);
    }

    void refreshList(MedicineEditView view, RecyclerView recycler, List<MedicineBean.MedicineItemBean> list,
                     TextView name, TextView unit, NextView time, NextView method, NextView day, TextView remark) {

//        while (mDatas.size() > 1) {
//            mDatas.removeLast();
//        }

        mDatas.clear();

        if (null == list || list.size() == 0 || null == name || null == unit) {
            view.refreshList(recycler);
            return;
        }

        final String names = name.getText().toString().trim();
        final String units = unit.getText().toString().trim();

        for (MedicineBean.MedicineItemBean model : list) {

            final boolean ok1 = names.equals(model.getMname());
            final boolean ok2 = units.equals(model.getDose_name());
            if (!ok1 || !ok2) continue;

            time.setText(model.getPeriod_begindate());
            method.setText(model.getMethod());
            day.setText(calcuDay(model.getPeriod_length()));
            remark.setText(model.getRemark());

//            while (mDatas.size() > 1) {
//                mDatas.removeLast();
//            }

            final List<MedicineBean.MedicineItemBean.MedicineItemDetailBean> list2 = model.getUse_detail();
            if (null != list2 && list2.size() > 0) {
                mDatas.addAll(list2);
            }
            break;
        }
        view.refreshList(recycler);
    }

    void saveMedicine(MedicineEditView view, RecyclerView recycler, ArrayList<MedicineBean.MedicineItemBean> upList, long patient_id, int positions) {

        if (null == view && null == recycler) return;

        final RecyclerView.Adapter adapter = recycler.getAdapter();
        if (null == adapter || !(adapter instanceof BaseCommonAdapter)) return;

        BaseCommonAdapter adapter1 = (BaseCommonAdapter) adapter;
        LinearLayout head = adapter1.getHead();
        if (null == head) return;

        // 药品名称
        TextView name = head.findViewById(R.id.activity_home_medicine_edit_head_names);
        String medicineName = name.getText().toString().trim();
        if (TextUtils.isEmpty(medicineName)) {
            ToastUtil.showToast("药品名称不能为空");
            return;
        }

        // 药品规格
        TextView unit = head.findViewById(R.id.activity_home_medicine_edit_head_units);
        String medicineUnit = unit.getText().toString().trim();
        if (TextUtils.isEmpty(medicineUnit)) {
            ToastUtil.showToast("药品规格不能为空");
            return;
        }

        // 服药时间
        NextView time = head.findViewById(R.id.home_medicine_edit_head_time);
        String medicineTime = time.getText();
        if (null == medicineTime) {
            ToastUtil.showToast("开始时间不能为空");
            return;
        }

        // 服药方法
        NextView method = head.findViewById(R.id.home_medicine_edit_head_method);
        String medicineMethod = method.getText();
        if (null == medicineMethod) {
            ToastUtil.showToast("服药方法不能为空");
            return;
        }

        // 服药周期
        NextView day = head.findViewById(R.id.home_medicine_edit_head_day);
        String medicineLength = day.getText();
        if (null == medicineLength) {
            ToastUtil.showToast("服药天数不能为空");
            return;
        }

        // 备注
        TextView remark = head.findViewById(R.id.home_medicine_edit_head_remark);
        String medicineRemark = remark.getText().toString().trim();

        if (mDatas.size() <= 1) {
            ToastUtil.showToast("服药详情不能为空!");
            return;
        }



        // 删除占位
        LinkedList<MedicineBean.MedicineItemBean.MedicineItemDetailBean> subList = new LinkedList<>();
        subList.addAll(mDatas);
        subList.removeFirst();

        for (MedicineBean.MedicineItemBean.MedicineItemDetailBean mData:subList) {
            if(mData.getUse_number() == 0.0) {
                ToastUtil.showToast("服药单次量不能为0!");
                return;
            }
        }

        // 新增药品时, 如果历史药单中存在规格名字相同的药品时, 视为修改药品
        if (positions == -1) {
            for (MedicineBean.MedicineItemBean temp : upList) {
                final String mname = temp.getMname();
                final String dosename = temp.getDose_name();
                if (medicineName.equals(mname) && medicineUnit.equals(dosename)) {
                    positions = upList.indexOf(temp);
                    break;
                }
            }
        }

        MedicineBean.MedicineItemBean oldModel = null;
        MedicineBean.MedicineItemBean newModel;

        // 新增药单
        if (positions == -1) {

            newModel = new MedicineBean.MedicineItemBean();
            newModel.setMname(medicineName);
            newModel.setDose_name(medicineUnit);
            newModel.setPeriod_begindate(medicineTime);
            newModel.setUse_interval(calcuMethod(medicineMethod));
            newModel.setPeriod_length(calcuLength(medicineLength));
            newModel.setRemark(medicineRemark);
            newModel.setUse_detail(subList);
            upList.add(0, newModel);

            // 新增药品
            String record = BaseApp.getResource().getString(R.string.home_medicine_edit_record_add, medicineName, medicineMethod, subList.size());
            SpannableUtil.append(record);
            SpannableUtil.newline();
        }
        // 修改药单
        else {
            oldModel = upList.get(positions);
            newModel = new MedicineBean.MedicineItemBean();
            newModel.setMname(medicineName);
            newModel.setDose_name(medicineUnit);
            newModel.setPeriod_begindate(medicineTime);
            newModel.setUse_interval(calcuMethod(medicineMethod));
            newModel.setPeriod_length(calcuLength(medicineLength));
            newModel.setRemark(medicineRemark);
            newModel.setUse_detail(subList);
            upList.set(positions, newModel);

            // 修改时间
            final String oldTime = oldModel.getPeriod_begindate();
            if (!medicineTime.equals(oldTime)) {
                String record = BaseApp.getStrings(R.string.home_medicine_edit_record_date, medicineName, oldTime, medicineTime);
                SpannableUtil.append(record);
                SpannableUtil.newline();
            }

            // 修改方法
            CharSequence oldMethod = oldModel.getMethod();
            if (!medicineMethod.equals(oldMethod)) {
                String record = BaseApp.getStrings(R.string.home_medicine_edit_record_method, medicineName, oldMethod, medicineMethod);
                SpannableUtil.append(record);
                SpannableUtil.newline();
            }

            // 修改天数
            CharSequence oldLength = calcuDay(oldModel.getPeriod_length());
            if (!medicineLength.equals(oldLength)) {
                String record = BaseApp.getStrings(R.string.home_medicine_edit_record_day, medicineName, oldLength, medicineLength);
                SpannableUtil.append(record);
                SpannableUtil.newline();
            }

            // 修改备注
            CharSequence oldRemark = oldModel.getRemark();
            if (!TextUtils.isEmpty(oldRemark) && !medicineRemark.equals(oldRemark)) {
                String record = BaseApp.getStrings(R.string.home_medicine_edit_record_remark, medicineName, oldRemark, medicineRemark);
                SpannableUtil.append(record);
                SpannableUtil.newline();
            }

            final List<MedicineBean.MedicineItemBean.MedicineItemDetailBean> detailList = oldModel.getUse_detail();
            if (null != detailList && detailList.size() > 0) {

                // 修改次数
                if (!subList.isEmpty() && subList.size() != detailList.size()) {
                    String record = BaseApp.getResource().getString(R.string.home_medicine_edit_record_number, medicineName, detailList.size(), subList.size());
                    SpannableUtil.append(record);
                    SpannableUtil.newline();
                }

                // 修改剂量
                for (int i = 0; i < Math.min(subList.size(), detailList.size()); i++) {

                    if (i >= subList.size()) break;

                    MedicineBean.MedicineItemBean.MedicineItemDetailBean olds = detailList.get(i);
                    MedicineBean.MedicineItemBean.MedicineItemDetailBean news = subList.get(i);
                    if (news.getUse_number() == olds.getUse_number()) continue;

                    String record = BaseApp.getStrings(R.string.home_medicine_edit_record_value, medicineName, news.getUse_order(), olds.getUse_number(), news.getUse_number());
                    SpannableUtil.append(record);
                    SpannableUtil.newline();
                }
            }
        }

        String editcontent = SpannableUtil.build().toString();
        Boolean isEdit = (!TextUtils.isEmpty(editcontent) && "\n" != editcontent);

        final HashMap<String, Object> map = new HashMap<>();
        map.put(PRESCRIPTION_DATE, getDate());
        map.put(JSON_CONTENT, upList);
        map.put(OLD_DATA, oldModel);
        map.put(NEW_DATA, newModel);

        if ("".equals(editcontent))
            map.put(JSON_RECORD, NULL);
        else{
            MedicineRecoedBean.MedicineRecoedItemBean.MedicineRecoedContentBean upJsonRecord = new MedicineRecoedBean.MedicineRecoedItemBean.MedicineRecoedContentBean();
            upJsonRecord.setEditorid(getPatientId());
            upJsonRecord.setEdittime(getMinute());
            upJsonRecord.setEditname("本人");
            upJsonRecord.setEditortype(2);
            upJsonRecord.setEditcontent(editcontent.endsWith("\n") ? editcontent.substring(0, editcontent.length() - 1) : editcontent);
            map.put(JSON_RECORD, upJsonRecord);
        }


        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_5_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveMedicine(params);

        final int finalPositions = positions;
        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                view.toast(finalPositions == -1 ? "新增失败" : "修改失败");
            }

            @Override
            public void modelSucc() {


                view.toast(finalPositions == -1 ? "新增成功" : "修改成功");
                Intent intent = new Intent();
                intent.putExtra(MedicineEditActivity.MODEL, newModel);
                intent.putExtra(MedicineEditActivity.EDIT_POSITION, finalPositions);
                intent.putExtra(MedicineEditActivity.EDIT_TYPE, finalPositions == -1 ? MedicineEditActivity.EDIT_ADD : MedicineEditActivity.EDIT_MODIFY);
                view.goBack(intent);
            }
        });
    }

    void deleteMedicine(MedicineEditView view, ArrayList<MedicineBean.MedicineItemBean> upList, int positions) {

        if (null == view || positions >= upList.size()) return;

        final MedicineBean.MedicineItemBean oldModel = upList.remove(positions);
        final HashMap<String, Object> map = new HashMap<>();
        map.put(PRESCRIPTION_DATE, getDate());
        map.put(JSON_CONTENT, upList);
        map.put(OLD_DATA, oldModel);
        map.put(NEW_DATA, NULL);

        MedicineRecoedBean.MedicineRecoedItemBean.MedicineRecoedContentBean upJsonRecord = new MedicineRecoedBean.MedicineRecoedItemBean.MedicineRecoedContentBean();
        upJsonRecord.setEditorid(getPatientId());
        upJsonRecord.setEdittime(getMinute());
        upJsonRecord.setEditname("本人");
        upJsonRecord.setEditcontent(BaseApp.getStrings(R.string.home_medicine_edit_record_delete, oldModel.getMname()));
        map.put(JSON_RECORD, upJsonRecord);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_5_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveMedicine(params);

        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                view.toast("删除失败");
            }

            @Override
            public void modelSucc() {
                view.toast("删除成功");
                Intent intent = new Intent();
                intent.putExtra(MedicineEditActivity.EDIT_POSITION, positions);
                intent.putExtra(MedicineEditActivity.EDIT_TYPE, MedicineEditActivity.EDIT_DELETE);
                view.goBack(intent);
            }
        });
    }

    void editMedicine(MedicineEditView view, RecyclerView recycler, String hour, String minute, int position) {
        if (null == view || null == recycler || TextUtils.isEmpty(hour) || TextUtils.isEmpty(minute) || position < 0)
            return;
        MedicineBean.MedicineItemBean.MedicineItemDetailBean model = mDatas.get(position);
        //model.setUse_time(getCalendar() + " " + hour + ":" + minute + ":00");
        model.setUse_time(hour + ":" + minute +":00" );
        Collections.sort(mDatas,new TimeComparator());

        view.refreshList(recycler);
    }

    int isBigTime(String t1,String t2){
        if ("".equals(t2))
            return 1;
        if ((t1.length()!=8) || (t2.length() != 8))
            return -1;

        int i = 0;
        for (;i < 8;i++){
            if(t1.charAt(i) > t2.charAt(i))
                return 1;
            if (t1.charAt(i) < t2.charAt(i))
                return -1;
        }
        return 0;
    }

    private final String calcuDay(int length) {
        if (length == 0) {
            return "长期";
        } else if (length == 1) {
            return "1天";
        } else if (length == 2) {
            return "2天";
        } else if (length == 3) {
            return "3天";
        } else if (length == 5) {
            return "5天";
        } else if (length == 7) {
            return "1周";
        } else if (length == 30) {
            return "1月";
        } else if (length == 183) {
            return "半年";
        } else {
            return length + "天";
        }
    }

    private final int calcuLength(String length) {
        if ("长期".equalsIgnoreCase(length)) {
            return 0;
        } else if ("1天".equalsIgnoreCase(length)) {
            return 1;
        } else if ("2天".equalsIgnoreCase(length)) {
            return 2;
        } else if ("3天".equalsIgnoreCase(length)) {
            return 3;
        } else if ("5天".equalsIgnoreCase(length)) {
            return 5;
        } else if ("1周".equalsIgnoreCase(length)) {
            return 7;
        } else if ("1月".equalsIgnoreCase(length)) {
            return 30;
        } else if ("半年".equalsIgnoreCase(length)) {
            return 183;
        } else {
            try {
                return Integer.parseInt(length.substring(0,length.length()-1));
            } catch (Exception e) {
                LogUtil.e("", e.getMessage(), e);
                return 1;
            }
        }
    }

    private final int calcuMethod(String method) {

        if ("每周服用".equals(method)) {
            return 7;
        } else if ("每月服用".equals(method)) {
            return 30;
        } else if ("每天服用".equals(method)) {
            return 1;
        } else if ("隔天服用".equals(method)) {
            return 2;
        } else {
            return 3;
        }
    }

    private final void calcuTime() {

        for (MedicineBean.MedicineItemBean.MedicineItemDetailBean it : mDatas) {
            if (it.getMultType() == MultModel.TYPE_0) continue;
            final int position = mDatas.indexOf(it);
            switch (position) {
                case 1:
                    if (mDatas.size() == 3) {
                        it.setUse_time(getHms("09:00"));
                    } else {
                        it.setUse_time(getHms("08:00"));
                    }
                    break;
                case 2:
                    if (mDatas.size() == 3) {
                        it.setUse_time(getHms("21:00"));
                    } else if (mDatas.size() == 4) {
                        it.setUse_time(getHms("16:00"));
                    } else {
                        it.setUse_time(getHms("12:00"));
                    }
                    break;
                case 3:
                    if (mDatas.size() == 4) {
                        it.setUse_time(getHms("22:00"));
                    } else {
                        it.setUse_time(getHms("18:00"));
                    }
                    break;
                case 4:
                    it.setUse_time(getHms("22:00"));
                    break;
                default:
                    it.setUse_time(getHms("23:00"));
            }
        }
    }

    @Override
    public void recycler() {
    }


    public  class TimeComparator implements Comparator<MedicineBean.MedicineItemBean.MedicineItemDetailBean>{
        @Override
        public int compare(MedicineBean.MedicineItemBean.MedicineItemDetailBean o1, MedicineBean.MedicineItemBean.MedicineItemDetailBean o2) {
            return isBigTime(o1.getUse_time(), o2.getUse_time());
        }
    }
}
